<template>
  <view class="container">
    <view class="header">
      <text class="title">个人中心</text>
    </view>
    <view class="profile-card">
      <view class="avatar-section">
        <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="avatar" :src="avatarUrl || '/static/images/default-avatar.png'" />
        </button>
        <input class="name-input" type="nickname" v-model="nickname" placeholder="请输入昵称" />
      </view>
      <view class="balance-section">
        <text class="label">昨日收益</text>
        <text class="value">¥{{ yesterdayEarnings }}</text>
      </view>
      <view class="total-section">
        <text class="label">累计收益</text>
        <text class="value">¥{{ totalEarnings }}</text>
      </view>
      <view class="actions">
        <view class="action-item" @click="goToEarnings">
          <text class="action-text">收益统计</text>
          <text class="action-arrow">></text>
        </view>
        <view class="action-item" @click="goToRecords">
          <text class="action-text">收益记录</text>
          <text class="action-arrow">></text>
        </view>
        <view class="action-item" @click="goToHistory">
          <text class="action-text">历史订单</text>
          <text class="action-arrow">></text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/user'
import { storeToRefs } from 'pinia'
import { uploadToOSS, ensureStsTokenValid, fetchAndScheduleStsToken, clearStsTokenTimer } from '@/utils/oss'
import { getYesterdayEarnings, getTotalEarnings } from '@/api/earnings'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

// 收益数据
const yesterdayEarnings = ref('0.00')
const totalEarnings = ref('0.00')

const avatarUrl = computed({
  get: () => userInfo.value?.avatar || '/static/images/default-avatar.png',
  set: (val) => {
    updateProfileField('avatar', val)
  }
})
const nickname = computed({
  get: () => userInfo.value?.nickname || '',
  set: (val) => {
    updateProfileField('nickname', val)
  }
})

const updateProfileField = async (field, value) => {
  try {
    const payload = {
      id: userInfo.value.id,
      nickname: field === 'nickname' ? value : userInfo.value.nickname,
      avatar: field === 'avatar' ? value : userInfo.value.avatar
    }
    await userStore.updateProfile(payload)
    uni.showToast({ title: '保存成功', icon: 'success' })
  } catch (e) {
    uni.showToast({ title: '保存失败', icon: 'none' })
  }
}

const onChooseAvatar = async (e) => {
  const tempUrl = e.detail.avatarUrl
  try {
    uni.showLoading({ title: '上传中...' })
    await ensureStsTokenValid()
    const ossUrl = await uploadToOSS(tempUrl)
    avatarUrl.value = ossUrl
    uni.showToast({ title: '头像上传成功', icon: 'success' })
  } catch (err) {
    console.error('头像上传失败:', err)
    uni.showToast({ title: '头像上传失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

onMounted(async () => {
  fetchAndScheduleStsToken()
  await loadEarningsData()
})

// 加载收益数据
const loadEarningsData = async () => {
  try {
    if (userStore.deliveryId) {
      const [yesterdayRes, totalRes] = await Promise.all([
        getYesterdayEarnings(userStore.deliveryId),
        getTotalEarnings(userStore.deliveryId)
      ])
      yesterdayEarnings.value = yesterdayRes.data || '0.00'
      totalEarnings.value = totalRes.data || '0.00'
    }
  } catch (error) {
    console.error('获取收益数据失败:', error)
  }
}
onUnmounted(() => {
  clearStsTokenTimer()
})

// 跳转到收益统计
const goToEarnings = () => {
  uni.navigateTo({
    url: '/pages/profile/earnings'
  })
}

// 跳转到收益记录
const goToRecords = () => {
  uni.navigateTo({
    url: '/pages/profile/records'
  })
}

// 跳转到历史订单
const goToHistory = () => {
  uni.navigateTo({
    url: '/pages/profile/history'
  })
}

</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: $bg-gradient;
  padding: 0;
}

.header {
  padding: 80rpx 40rpx 60rpx;
  text-align: center;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 120rpx;
    height: 8rpx;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 4rpx;
  }
}

.title {
  font-size: 48rpx;
  font-weight: 700;
  color: #ffffff;
  text-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
  margin-bottom: 16rpx;
}

.profile-card {
  @include card-style;
  margin: 0 40rpx 40rpx;
  padding: 48rpx;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(30rpx);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 8rpx;
    background: $bg-gradient;
  }
}

.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.avatar-btn {
  padding: 0;
  background: none;
  border: none;
  margin-right: 30rpx;
  position: relative;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  border: 6rpx solid #ffffff;
  box-shadow: $shadow-md;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
}

.name-input {
  font-size: 38rpx;
  font-weight: 600;
  border: none;
  background: transparent;
  outline: none;
  color: $text-primary;
  flex: 1;
  text-align: center;
  margin-top: 24rpx;
}

.balance-section {
  background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);
  border-radius: 32rpx;
  padding: 40rpx;
  margin-bottom: 32rpx;
  text-align: center;
  box-shadow: $shadow-primary;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
    animation: shimmer 3s ease-in-out infinite;
  }
}

.total-section {
  background: linear-gradient(135deg, $accent-color 0%, $secondary-color 100%);
  border-radius: 32rpx;
  padding: 40rpx;
  margin-bottom: 48rpx;
  text-align: center;
  box-shadow: $shadow-success;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
    animation: shimmer 3s ease-in-out infinite 1.5s;
  }
}

@keyframes shimmer {
  0%, 100% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
  50% { transform: translateX(100%) translateY(100%) rotate(45deg); }
}

.label {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  display: block;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.value {
  font-size: 52rpx;
  font-weight: 700;
  color: #ffffff;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  padding: 0 40rpx 40rpx;
}

.action-item {
  @include card-style;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(30rpx);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: $bg-gradient-light;
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  
  &:active {
    transform: translateY(2rpx);
    
    &::before {
      opacity: 1;
    }
  }
}

.action-text {
  font-size: 34rpx;
  color: $text-primary;
  font-weight: 600;
  position: relative;
  z-index: 1;
}

.action-arrow {
  font-size: 32rpx;
  color: $primary-color;
  font-weight: 600;
  position: relative;
  z-index: 1;
}
</style>